// const Service = require('egg').Service;

// class ArrayService extends Service {
module.exports = {
    //获取数组————根据区间
    //areaStr: [1,1)、[1,1]、(1,1)……  “[”或：“]”表示包含，“（”或“）”表示不包含  step: 相邻数的差值
    byArea(areaStr, step = 1) {
        let max = 0, min = 0, leftBracket = "", rightBracket = "";
        let areaArr = [], endArr = [];
        if (typeof areaStr !== "string") {
            throw new Error("参数area必须是字符串类型");
        }
        areaStr = areaStr.replace(/\s/g, "");
        areaArr = areaStr.replace(/[\[\]\(\)]/g, "").split(",");
        min = parseInt(areaArr[0]);
        max = parseInt(areaArr[1]);
        leftBracket = areaStr.charAt(0);
        rightBracket = areaStr.charAt(areaStr.length - 1);
        for (let i = min; i <= max; i += step) {
            if (i == min) {
                leftBracket == "[" && endArr.push(min);
            } else if (i == max) {
                rightBracket == "]" && endArr.push(max);
            } else {
                endArr.push(i);
            }
        }
        return endArr;
    },
    //数组排序
    // type: asc(升序) desc(降序) no(无序)
    order(arr, type = "asc") {
        let isNumArr = arr.every(item => typeof item === "number");
        if (isNumArr) {
            switch (type) {
                case "no": return arr.sort(() => Math.random() > .5 ? -1 : 1);
                case "asc": return arr.sort((a, b) => a - b);
                case "desc": return arr.sort((a, b) => b - a);
                default: break;
            }
        } else {
            switch (type) {
                case "no": return arr.sort(() => Math.random() > .5 ? -1 : 1);
                case "asc": return arr.sort();
                case "desc": return arr.sort().reverse();
                default: break;
            }
        }
    },
    //数组深拷贝
    clone(arr) {
        let newArr = [];
        arr.forEach(item => {
            newArr.push(item);
        });
        return newArr;
    },
    //转成sql语句的where字符串
    //arr [[key,val],[key,operator,val]]，无operator的默认为“=”
    toSqlWhereStr(arr) {
        let str = "";
        let isFirst = true;
        arr.forEach((item, ind) => {
            ind == 0 && (str += "where ");
            if (item.length === 2) {
                item[2] = item[1];
                item[1] = "=";
            }
            if (item[2] !== undefined) {
                !isFirst && (str += "and ");
                str += `${item[0]} ${item[1]} ${item[2]} `;
                isFirst = false;
            }
        })
        return str;
    }
}

// module.exports = ArrayService;